package com.panda.handler.exception;


import com.panda.enums.AppHttpCodeEnum;
import com.panda.exception.SystemException;
import com.panda.utils.RespondResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

/**
 * @Author: panda
 * @Date: 2022-05-18 16:05
 * @Description: 全局异常处理，没配置的话，报错信息会很模糊，前台收不到 copy
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获异常（最大的那个异常）
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    public RespondResult exceptionHandler(Exception exception) {
        log.error("出现异常。", exception);
        return RespondResult.errorResult(AppHttpCodeEnum.SYS_ERROR, exception.getMessage());
    }

    /**
     * 捕获系统异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(SystemException.class)
    public RespondResult systemExceptionHandler(SystemException exception) {
        log.error("出现异常。", exception);
        return RespondResult.errorResult(exception.getCode(), exception.getMsg());
    }

    /**
     * 捕获HttpRequestMethodNotSupportedException异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public RespondResult methodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException exception) {
        log.error("出现异常。", exception);
        return RespondResult.errorResult(AppHttpCodeEnum.SYS_ERROR, "请求方法不支持");
    }


    /**
     * 捕获HttpRequestMethodNotSupportedException异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(BadCredentialsException.class)
    public RespondResult usernameOrPasswordException(BadCredentialsException exception) {
        log.error("出现异常。", exception);
        return RespondResult.errorResult(AppHttpCodeEnum.SYS_ERROR, "用户名或密码错误");
    }


    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public RespondResult handleParameterVerificationException(Exception e) {
        // log.error(" handleParameterVerificationException has been invoked", e);
        String msg = null;
        if (e instanceof MethodArgumentNotValidException) {
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            // getFieldError获取的是第一个不合法的参数(P.S.如果有多个参数不合法的话)
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                msg = fieldError.getDefaultMessage();
            }
        } else if (e instanceof BindException) {
            // getFieldError获取的是第一个不合法的参数(P.S.如果有多个参数不合法的话)
            FieldError fieldError = ((BindException) e).getFieldError();
            if (fieldError != null) {
                msg = fieldError.getDefaultMessage();
            }
        } else if (e instanceof ConstraintViolationException) {
            /*
             * ConstraintViolationException的e.getMessage()形如
             *     {方法名}.{参数名}: {message}
             *  这里只需要取后面的message即可
             */
            msg = e.getMessage();
            if (msg != null) {
                int lastIndex = msg.lastIndexOf(':');
                if (lastIndex >= 0) {
                    msg = msg.substring(lastIndex + 1).trim();
                }
            }
            /// ValidationException 的其它子类异常
        } else {
            msg = e.getMessage();
        }
        return RespondResult.errorResult(400, msg);
    }

}
